package com.mydemo.admin.config;

import com.mydemo.common.Constant;
import com.mydemo.common.pojo.LoginUser;
import com.mydemo.common.pojo.Permission;
import com.mydemo.common.pojo.Role;
import com.mydemo.common.utils.SecurityUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 权限逻辑
 * @author Last_Island
 * @version 1.0
 */
@Component("authz")
public class AuthorizationLogic {
    /**
     * 判断用户是否有权限
     * @param authority 权限标识符
     * @return
     */
    public boolean decide(String authority) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<Role> roles = loginUser.getRoles();
        if (SecurityUtils.isAdmin())
            return true;
        for (Role role : roles) {
            if (role.getRoleKey().equals(Constant.ADMIN_ROLE_KEY)){
                return true;
            }
            List<Permission> permissions = role.getPermissions();
            int indexOf = permissions.indexOf(new Permission(authority));
            if (indexOf != -1)
                return true;
        }
        return false;
    }
}
